#!/bin/bash

# 日志文件路径
LOG_FILE="/var/log/sd-mount.log"

# 日志记录函数
log_message() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$LOG_FILE"
}

ACTION=$1
DEVICE=$2
MNT_BASE="/media"
FS_TYPE="exfat"

log_message "======ACTION=$ACTION DEVICE=$DEVICE======"

case "$ACTION" in
    add)
        log_message "挂载SD卡: $DEVICE"
        
        # 检查设备是否存在
        if [ ! -e "/dev/$DEVICE" ]; then
            log_message "错误: 设备 /dev/$DEVICE 不存在"
            exit 1
        fi
        
        # 创建挂载点
        MNT_PATH="${MNT_BASE}/${DEVICE}"
        mkdir -p "$MNT_PATH"
        
        # 尝试挂载
        if mount -t "$FS_TYPE" "/dev/$DEVICE" "$MNT_PATH" 2>> "$LOG_FILE"; then
            log_message "挂载成功: $DEVICE 到 $MNT_PATH"
        else
            log_message "挂载失败: $DEVICE，尝试其他文件系统"
            # 尝试自动检测文件系统
            if mount "/dev/$DEVICE" "$MNT_PATH" 2>> "$LOG_FILE"; then
                log_message "自动挂载成功: $DEVICE 到 $MNT_PATH"
            else
                log_message "所有挂载尝试都失败: $DEVICE"
                rmdir "$MNT_PATH"
                exit 1
            fi
        fi
        ;;
        
    remove)
        log_message "卸载SD卡: $DEVICE"
        
        MNT_PATH="${MNT_BASE}/${DEVICE}"
        
        if mountpoint -q "$MNT_PATH"; then
            # 正常卸载
            if umount "$MNT_PATH" 2>> "$LOG_FILE"; then
                rmdir "$MNT_PATH"
                log_message "卸载成功: $DEVICE"
            else
                # 强制卸载
                log_message "正常卸载失败，尝试强制卸载: $DEVICE"
                umount -l "$MNT_PATH"
                rmdir "$MNT_PATH" 2>/dev/null
                log_message "强制卸载完成: $DEVICE"
            fi
        else
            log_message "挂载点不存在或未挂载: $MNT_PATH"
            rmdir "$MNT_PATH" 2>/dev/null
        fi
        ;;
        
    *)
        log_message "错误: 未知操作 $ACTION"
        exit 1
        ;;
esac

exit 0